{% extends "base.html" %}

{% block title %}价格预测{% endblock %}

{% block content %}
<div class="container-fluid">
    <h2 class="mt-4 text-success">不同类型农产品价格未来预测</h2>
    <hr>

    <!-- Controls -->
    <div class="card shadow-sm mb-4">
        <div class="card-body">
            <div class="row g-3 align-items-end">
                <div class="col-md-4">
                    <label for="category-select" class="form-label">产品大类</label>
                    <select id="category-select" class="form-select">
                        {% for category in categorized_products %}
                            <option value="{{ category }}">{{ category }}</option>
                        {% endfor %}
                    </select>
                </div>
                <div class="col-md-4">
                    <label for="product-select" class="form-label">具体产品</label>
                    <select id="product-select" class="form-select"></select>
                </div>
                <div class="col-md-2">
                    <label for="prediction-days" class="form-label">预测天数</label>
                    <select id="prediction-days" class="form-select">
                        <option value="3" selected>3天</option>
                        <option value="7">7天</option>
                        <option value="14">14天</option>
                        <option value="30">30天</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <button id="refresh-prediction" class="btn btn-success w-100">
                        <i class="fas fa-sync-alt me-1"></i> 刷新预测
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Chart -->
    <div class="card shadow-sm mb-4">
        <div class="card-body">
            <div id="loading-spinner" class="text-center py-5" style="display: none;">
                <div class="spinner-border text-success" role="status">
                    <span class="visually-hidden">加载中...</span>
                </div>
                <p class="mt-2">正在努力预测中...</p>
            </div>
            <div id="chart-container" style="height: 450px;"></div>
            <div id="error-container" class="alert alert-danger mt-3" style="display: none;"></div>
        </div>
    </div>

    <!-- Analysis Section -->
    <div class="row">
        <!-- Trend Analysis -->
        <div class="col-lg-6 mb-4">
            <div class="card shadow-sm h-100">
                <div class="card-header bg-success text-white">
                    <i class="fas fa-chart-line me-2"></i>预测趋势分析
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-6 mb-3">
                            <strong>预测趋势</strong>
                            <p id="analysis-trend" class="fs-4 text-success mb-0">--</p>
                        </div>
                        <div class="col-6 mb-3">
                            <strong>置信度</strong>
                            <p id="analysis-confidence" class="fs-4 text-primary mb-0">--</p>
                        </div>
                        <div class="col-6">
                            <strong>预测最高价</strong>
                            <p id="analysis-max-price" class="fs-4 text-danger mb-0">--</p>
                        </div>
                        <div class="col-6">
                            <strong>预测最低价</strong>
                            <p id="analysis-min-price" class="fs-4 text-info mb-0">--</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- Investment Suggestion -->
        <div class="col-lg-6 mb-4">
            <div class="card shadow-sm h-100">
                <div class="card-header bg-warning text-dark">
                    <i class="fas fa-lightbulb me-2"></i>投资建议
                </div>
                <div class="card-body">
                    <div class="alert alert-warning" role="alert">
                        <h4 class="alert-heading"><i class="fas fa-exclamation-triangle me-2"></i>风险提示</h4>
                        <p>所有预测均基于历史数据和简化模型，仅供参考，不构成任何投资决策依据。市场有风险，投资需谨慎。</p>
                    </div>
                    <p id="analysis-suggestion" class="text-dark">请先刷新预测以获取建议。</p>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    const categorizedProducts = {{ categorized_products | tojson | safe }};
    const categorySelect = document.getElementById('category-select');
    const productSelect = document.getElementById('product-select');
    const daysSelect = document.getElementById('prediction-days');
    const refreshBtn = document.getElementById('refresh-prediction');

    const loadingSpinner = document.getElementById('loading-spinner');
    const chartContainer = document.getElementById('chart-container');
    const errorContainer = document.getElementById('error-container');

    function updateProductOptions() {
        const selectedCategory = categorySelect.value;
        const products = categorizedProducts[selectedCategory] || [];
        productSelect.innerHTML = '';
        if (products.length > 0) {
            products.forEach(product => {
                const option = document.createElement('option');
                option.value = product;
                option.textContent = product;
                productSelect.appendChild(option);
            });
        } else {
            const option = document.createElement('option');
            option.textContent = '该分类下无产品';
            productSelect.appendChild(option);
        }
    }

    async function fetchPredictionData() {
        const productType = productSelect.value;
        const days = daysSelect.value;

        if (!productType || productSelect.selectedOptions[0].textContent === '该分类下无产品') {
            errorContainer.textContent = '请选择一个有效的产品进行预测。';
            errorContainer.style.display = 'block';
            chartContainer.style.display = 'none';
            return;
        }

        loadingSpinner.style.display = 'block';
        chartContainer.style.display = 'none';
        errorContainer.style.display = 'none';
        clearAnalysis();

        try {
            const params = new URLSearchParams({ product_type: productType, days: days });
            const response = await fetch(`{{ url_for("api_price_prediction") }}?${params}`);
            const res = await response.json();
            
            if (res.error) {
                errorContainer.textContent = res.error;
                errorContainer.style.display = 'block';
            } else {
                const chart = JSON.parse(res.chart_json);
                Plotly.newPlot(chartContainer, chart.data, chart.layout, { responsive: true });
                chartContainer.style.display = 'block';

                document.getElementById('analysis-trend').textContent = res.trend;
                document.getElementById('analysis-confidence').textContent = res.confidence;
                document.getElementById('analysis-max-price').textContent = res.pred_high;
                document.getElementById('analysis-min-price').textContent = res.pred_low;
                document.getElementById('analysis-suggestion').textContent = getSuggestion(res.trend);
            }
        } catch (err) {
            errorContainer.textContent = '请求预测数据时发生网络或服务器错误。';
            errorContainer.style.display = 'block';
        } finally {
            loadingSpinner.style.display = 'none';
        }
    }
    
    function getSuggestion(trend) {
        if (trend === '上升趋势') {
            return '根据预测分析，建议适当增加库存，价格呈上升趋势。';
        } else if (trend === '下降趋势') {
            return '根据预测分析，建议谨慎补货，价格呈下降趋势。';
        } else {
            return '根据预测分析，价格走势平稳，按需补货即可。';
        }
    }

    function clearAnalysis() {
        document.getElementById('analysis-trend').textContent = '--';
        document.getElementById('analysis-confidence').textContent = '--';
        document.getElementById('analysis-max-price').textContent = '--';
        document.getElementById('analysis-min-price').textContent = '--';
        document.getElementById('analysis-suggestion').textContent = '请先刷新预测以获取建议。';
    }

    categorySelect.addEventListener('change', () => {
        updateProductOptions();
        fetchPredictionData();
    });
    
    refreshBtn.addEventListener('click', fetchPredictionData);
    productSelect.addEventListener('change', fetchPredictionData);
    daysSelect.addEventListener('change', fetchPredictionData);

    updateProductOptions();
    fetchPredictionData();
});
</script>
{% endblock %} 